package com.ecarx.camera.ui.main;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.ecarx.camera.R;
import com.ecarx.camera.constant.Constants;
import com.ecarx.camera.data.ThumbnailData;
import com.ecarx.camera.ui.BaseFragment;
import com.ecarx.camera.ui.camera.CameraFragment;
import com.ecarx.camera.ui.contract.IMainView;
import com.ecarx.camera.ui.main.adapter.MainFragmentStateAdapter;
import com.ecarx.camera.utils.DialogUtils;
import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.NaviUtils;
import com.ecarx.camera.utils.RadioBtnClickFilterUtils;
import com.ecarx.camera.utils.StorageUtils;
import com.ecarx.camera.utils.TestSwitchCamera;
import com.ecarx.camera.utils.Utils;
import com.ecarx.camera.worker.config.ConfigManager;
import com.ecarx.camera.worker.sound.SoundPlayManger;

public class MainFragment extends BaseFragment implements IMainView {

    private static final String TAG = "MainFragment";

    private TextView tvTitle;
    private RadioGroup naviBar;
    private RadioButton naviBarItemExterior;
    private RadioButton naviBarItemSettings;
    private ViewPager2 viewPager;
    private ImageView ibtnToGallery;

    private View mPrivacyNotAgreedShade;
    private View mPrivacySettingsShade;

    private MainFragmentStateAdapter fragmentStateAdapter;

    private ThumbnailData mInteriorThumbnail;

    private final RadioBtnClickFilterUtils mRadioBtnClickFilterUtils = new RadioBtnClickFilterUtils();

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initData() {
        super.initData();
        fragmentStateAdapter = new MainFragmentStateAdapter(this);
    }

    @Override
    protected void bindViews() {
        super.bindViews();
        mPrivacyNotAgreedShade = view.findViewById(R.id.privacy_not_agreed_shade);
        mPrivacySettingsShade = view.findViewById(R.id.privacy_settings_shade);
        tvTitle = view.findViewById(R.id.tv_title);
        naviBar = view.findViewById(R.id.navi_bar);
        naviBarItemExterior = view.findViewById(R.id.navi_bar_item_exterior);
        naviBarItemSettings = view.findViewById(R.id.navi_bar_item_settings);
        viewPager = view.findViewById(R.id.view_pager);
        ibtnToGallery = view.findViewById(R.id.ibtn_to_gallery);
        naviBar.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.navi_bar_item_exterior) {
                LogUtils.d(TAG, "tag_checked-> exterior");
                ibtnToGallery.setVisibility(View.GONE);
                if(fragmentStateAdapter!=null && fragmentStateAdapter.getCameraFragment()!=null){
                    fragmentStateAdapter.getCameraFragment().setCameraFacing(Constants.FacingType.EXTERIOR);
                }
                viewPager.setCurrentItem(0, false);
            }
            if (checkedId == R.id.navi_bar_item_settings) {
                LogUtils.d(TAG, "tag_checked-> settings");
                ibtnToGallery.setVisibility(View.GONE);
                viewPager.setCurrentItem(1, false);
            }
        });
        mRadioBtnClickFilterUtils.addRadioButton(naviBarItemExterior);

        int drawableOffset = Utils.getApp().getResources().getDimensionPixelSize(R.dimen.camera_main_navi_bar_ic_offset);
        naviBarItemExterior.setChecked(true);
        {
            int drawableTopWidth = Utils.getApp().getResources().getDimensionPixelSize(R.dimen.camera_main_navi_bar_item_drawable_top_width);
            Drawable drawableTop = ContextCompat.getDrawable(Utils.getApp(), R.drawable.camera_main_ic_exterior);
            drawableTop.setBounds(-drawableOffset, 0, drawableTopWidth - drawableOffset, Utils.getApp().getResources().getDimensionPixelSize(R.dimen.camera_main_navi_bar_item_drawable_top_width));
            naviBarItemExterior.setCompoundDrawablesRelative(null, drawableTop, null, null);
        }
        {
            int drawableTopWidth = Utils.getApp().getResources().getDimensionPixelSize(R.dimen.camera_main_navi_bar_item_drawable_top_width);
            Drawable drawableTop = ContextCompat.getDrawable(Utils.getApp(), R.drawable.camera_main_ic_settings);
            drawableTop.setBounds(-drawableOffset, 0, drawableTopWidth - drawableOffset, Utils.getApp().getResources().getDimensionPixelSize(R.dimen.camera_main_navi_bar_item_drawable_top_width));
            naviBarItemSettings.setCompoundDrawablesRelative(null, drawableTop, null, null);
        }
        viewPager.setAdapter(fragmentStateAdapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setUserInputEnabled(false);
        ibtnToGallery.setOnClickListener(v -> {
            ThumbnailData thumbnailData = (ThumbnailData) ibtnToGallery.getTag();
            if (thumbnailData != null) {
                NaviUtils.naviToGalleryPreview(getContext(), thumbnailData);
            }
        });

        // TODO: 2023/6/9 test
        TestSwitchCamera.test(naviBar, R.id.navi_bar_item_exterior);
    }

    @Override
    protected void initViews() {
        super.initViews();
        tvTitle.setTextColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_base_day_night_fg_color));
        for (int index = 0; index < naviBar.getChildCount(); index++) {
            View childView = naviBar.getChildAt(index);
            if (childView instanceof RadioButton) {
                DrawableCompat.setTintList(((RadioButton) childView).getCompoundDrawablesRelative()[1], ContextCompat.getColorStateList(Utils.getApp(), R.color.camera_main_selector_drawable_tint_color_navi_bar_item));
                ((RadioButton) childView).setTextColor(ContextCompat.getColorStateList(Utils.getApp(), R.color.camera_main_selector_text_color_navi_bar_item));
            } else {
                // 分割线
                childView.setBackgroundColor(ContextCompat.getColor(Utils.getApp(), R.color.camera_main_navi_bar_divider_color));
            }
        }
    }

    @Override
    protected void onResume(boolean firstResume) {
        super.onResume(firstResume);
        mRadioBtnClickFilterUtils.enableAllRadioButtons();
        if (firstResume) {
            showPrivatePolicyDialog();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG, "Lifecycle-> onCreate, this:" + this);
        SoundPlayManger.get().initSoundPool();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "Lifecycle-> onDestroy, this:" + this);
        if (mInteriorThumbnail != null) {
            mInteriorThumbnail.recycle();
        }
        SoundPlayManger.get().release();

        // TODO: 2023/6/9 test
        TestSwitchCamera.clear();
    }

    @Override
    public void setGalleryThumbnail(ThumbnailData thumbnailData) {
        if (thumbnailData != null) {
            if (thumbnailData.getFacingType() == Constants.FacingType.INTERIOR) {
                mInteriorThumbnail = thumbnailData;
            }
            ibtnToGallery.post(new Runnable() {
                @Override
                public void run() {
                    ibtnToGallery.setTag(thumbnailData);
                    LogUtils.d(TAG, "thumbnail-> setGalleryThumbnail: " + thumbnailData);
                    if (mInteriorThumbnail != null && mInteriorThumbnail.getBitmap() != null) {
                        ibtnToGallery.setImageBitmap(thumbnailData.getBitmap());
                    } else {
                        ibtnToGallery.setImageResource(R.drawable.camera_ic_default_thumbnail);
                    }
                }
            });
        }
    }

    /**
     * 显示或隐藏"设置中隐私协议弹窗时的背景遮罩"
     * @param isShown
     */
    public void showPrivacySettingsShade(boolean isShown) {
        mPrivacySettingsShade.setVisibility(isShown ? View.VISIBLE : View.GONE);
    }

    private void showPrivatePolicyDialog() {
        if (!ConfigManager.getInstance().isPrivatePrivacyAgreed()) {
            mPrivacyNotAgreedShade.setVisibility(View.VISIBLE);
            DialogUtils.showPrivatePolicyDialog(getChildFragmentManager(),
                    dialog -> {
                        mPrivacyNotAgreedShade.setVisibility(View.GONE);
                        ConfigManager.getInstance().setPrivatePrivacyAgreed(true);
                        dialog.dismiss();
                    }, null);
        } else {
            checkStorage();
        }
    }

    private void checkStorage() {
        StorageUtils.checkStorage(getChildFragmentManager());
    }
}
